﻿using Collection.Export.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WanPiJie.Products;
using Collection.Entities;
using Collection.Services;
using WanPiJie;

namespace Collection.Export.Services.Wanpijie
{
    /// <summary>
    /// 商品属性导出服务
    /// </summary>
    public class AttributeService : Service<Property>
    {
        /// <summary>
        /// 导出商品属性数据
        /// </summary>
        /// <param name="property">商品属性</param>
        /// <returns>商品的属性数据</returns>
        public override Property Import(Property property)
        {
            this.GeneralizeAttribute();
            var pa = property.ToProductAttribute();
            if (WpjSf.CategoryService.HasProductAttribute(pa.CatalogId, pa.AttributeId))
            {
                WpjSf.CategoryService.UpdateProductAttribute(pa.CatalogId, pa.AttributeId, pa.Name);
                this.OnUpdate(property);
            }
            else
            {
                WpjSf.CategoryService.AddProductAttribute(pa.CatalogId, pa.AttributeId, pa.Name);
                this.OnInsert(property);
            }
            return property;
        }

        /// <summary>
        /// 提取属性
        /// </summary>
        public void GeneralizeAttribute()
        {
            var properties = CollectionServiceFactory.CatalogService.GetProperties();
            foreach (var property in properties)
            {
                this.Import(new WanPiJie.Products.Attribute
                 {
                     ThirdId = property.Id,
                     Name = property.Name
                 });
            }
        }

        /// <summary>
        /// 导入属性数据
        /// </summary>
        /// <param name="attribute">属性对象</param>
        public void Import(WanPiJie.Products.Attribute attribute)
        {
            if (WpjSf.CategoryService.GetAttributeByThirdId(attribute.ThirdId) != null)
            {
                WpjSf.CategoryService.UpdateAttribute(attribute.ThirdId, attribute.Name);
            }
            else
            {
                WpjSf.CategoryService.AddAttribute(attribute.ThirdId, attribute.Name);
            }
        }
    }
}
